<?php
namespace app\middleware;

use Closure;
use app\service\JwtService;

class AuthMiddleware
{
    public function handle($request, Closure $next)
    {
        $authHeader = $request->header('Authorization');
        if (!$authHeader || !preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
            return json(['code' => 401, 'msg' => '请先登录'], 401);
        }

        $token = $matches[1];
        $payload = JwtService::verifyToken($token);
        if (!$payload) {
            return json(['code' => 401, 'msg' => '身份验证失败'], 401);
        }

        $request->user = $payload;

        return $next($request);
    }
}

